autocmd!
mapclear
mapclear!
noremap / <Esc>
noremap! / <Esc>
cnoremap / <C-C>
noremap  `/ /
noremap! `/ /
map [3~ 
map! [3~ 
map OP <F1>
map! OP <F1>
map OQ <F2>
map! OQ <F2>
map OR <F3>
map! OR <F3>
map OS <F4>
map! OS <F4>
map [15~ <F5>
map! [15~ <F5>
nnoremap <F9> <C-O>
nnoremap <F10> <C-I>
set nowrap hidden ignorecase smartcase incsearch backspace=2 linebreak 
set autoindent tabstop=4 history=150 mouse=a ttymouse=xterm 
set wildmode=list:longest,full display=lastline modeline t_Co=256
set wildmenu listchars=tab:>\ ,eol:<
syntax on
hi NonText ctermfg=238
hi SpecialKey ctermfg=238
hi Statement ctermfg=250
hi Constant ctermfg=255
hi Identifier ctermfg=123
hi ErrorMsg ctermbg=143 ctermfg=0
hi Search ctermbg=238
hi clear MatchParen 
hi MatchParen ctermfg=121
hi Pmenu ctermfg=121 ctermbg=238
hi PmenuSel ctermfg=121
au VimEnter * if !argc() | cd /sdcard-ext/vimhome | e main | en | so abbrev
au VimLeavePre * exe 'normal! mL'

cnorea <expr> we ((getcmdtype()==':' && getcmdpos()<4)? 'w\|e' :'we')
cnorea <expr> wf ((getcmdtype()==':' && getcmdpos()<4)? 
\ 'w\|e\|norm! gggqG':'we')
cnorea <expr> waq ((getcmdtype()==':' && getcmdpos()<5)? 'wa\|q':'waq')
cnorea <expr> ws ((getcmdtype()==':' && getcmdpos()<4)? 'w\|so%':'ws')
cnorea <expr> wd ((getcmdtype()==':' && getcmdpos()<4)? 'w\|bd':'wd')
cnorea <expr> wsd ((getcmdtype()==':' && getcmdpos()<5)? 'w\|so%\|bd':'wsd')

fun! PunchIn() "requires !export TZ=EST5EDT
	if bufname('%')!=#'Timecard'
		split Timecard
		let exitcmd='q'
	else
		let exitcmd='e #'
	endif
	let now=strftime("%l:%M %m/%d... punch [i]n / [o]ut /[q]?")
	echoh Constant | redraw | echo now 
	let io=nr2char(getchar())
	if io=~?'[io]'
		exe (search('^'.now[6:10])? '' : 'normal! Go'.now[6:10])
		exe 'normal! A'.(io==?'i'? ' ' : '>').now[0:4]
		redraw | echo "...done" | call getchar() | exe exitcmd 
	elseif io==?'q'
		exe exitcmd
	endif
	redraw | echo "" | echoh End	
endfun
nnoremap `T :call PunchIn()<CR>

hi clear StatusLine
hi StatusLine ctermfg=250 ctermbg=238
set stl=\ %l/%L\ %<%F%y%=%{strftime(\"%l:%M\ %b\ %d\ \")}
nnoremap <silent> K :exe 'se ls='.(&ls==2?0:2)<CR>

fun! InitTextFile()
	syntax region txtShow start=/\t/ end=/\t\|\S\n/
	syntax region txtHide start=/>\t/ end=/\t\|\S\n/
	hi link txtShow Constant
	hi link txtHide NonText
	if getline(1)=~'tw='	
		nnoremap <buffer> A }b$a
		nnoremap <buffer> I {w0i
	endif
endfun
au BufNewFile,BufRead *.txt call InitTextFile()
au BufNewFile *.txt exe "norm! i>\tvim: set nowrap ts=1 tw=66 fo=aw:\t"

let s:Menu=["'Empty String'[-1]",
\ "'!rm '.(expand('%:h')=='.'? '':expand('%:h').'/')"
\ .".(expand('%:t')[0]=='.'? '':'.').expand('%:t').'.swp'",
\ "'/mnt/sdcard/download/'",
\ "'/data/data/org.connectbot/files/kbox/'"]
let s:MenuStr=join(map(copy(s:Menu),
\ "v:key.' '.(len(v:val)>44? v:val[:20].' .. '.v:val[-20:] : v:val)"),"\n")
fun! InsertMenu()
	echoh Constant | echo s:MenuStr | echoh None
	return eval(s:Menu[str2nr(nr2char(getchar()))])
endfun
fun! BufferMenu()
	let bufstr="\n" | let idx=[0]
	for b in range(1, bufnr('$'))
		let bufstr.=buflisted(b)? (len(add(idx,b))-1)
		\ .(bufnr('%')==b? '*':' ').' '.matchstr(bufname(b),'[^/]*$')."\n":''
	endfor
	echoh Constant | echo bufstr | echoh None
	let sel=nr2char(getchar())
	if sel==?'x'
		let lst=join(map(split(input("Delete buffers ")),'idx[v:val]'))
		if lst
			exe 'redraw | bd! '.lst
			call BufferMenu()
		endif
	elseif str2nr(sel)
		exe 'redraw | b '.idx[sel]
	endif
endfun
nnoremap <F7> :call BufferMenu()<CR>
noremap! <F7> <C-R>=InsertMenu()<CR>

let s:Dots  =join(map(range(1,100),'"."'),'.')
let s:Dashes=join(map(range(1,100),'"-"'),'-')
let s:Spaces=join(map(range(1,100),'" "'),' ')
let s:Speed =[1,2,4,7,11,16,22,29,37,46,56]
let g:MouseMode='InitScroll'
fun! InitScroll()
	let s:vesave=&ve | se ve=all
	let s:prevR=winline()
	let s:prevC=wincol()
	let s:clickTime=reltime()
	let s:iniW=winnr()
	let g:MouseMode='OnScroll'
endfun
fun! OnScroll()
	if winnr()!=s:iniW
		exe 'se ve='.s:vesave
		let s:iniW=winnr()
		let g:MouseMode='OnResize'
		call OnResize()
	elseif eval(join(reltime(s:clickTime),'*1000000+').'>700000')
		norm! mv
		exe 'se ve='.s:vesave
		let g:MouseMode='OnVisual'
		call OnVisual()
	else
    	let difC=wincol()-s:prevC | let difR=winline()-s:prevR
    	let s:prevC+=difC | let s:prevR+=difR
		let cmd=(difC>0? difC."z\<left>":difC<0? (-difC)."z\<right>":'')
		\ .(difR>0? s:Speed[difR]."\<C-Y>":difR<0? s:Speed[-difR]."\<C-E>":'')
		if cmd
			let s:clickTime=reltime()
			exe 'norm! '.cmd
	    	redraw | echo s:Dots[2:line('w0')*&columns/line('$')]
	    elseif line('.')==line('$')
	    	exe "norm! \<C-Y>"
	    endif
	endif
endfun
fun! OnVisual()
	let cdiff=virtcol("'v")-wincol()
	let rdiff=line("'v")-line(".")
	echo rdiff.(s:Spaces[1:(cdiff>0? wincol():virtcol("'v"))]
	\ .s:Dashes[1:abs(cdiff)])[len(rdiff):]
	if line('.')==line('w$')
		exe "norm! \<C-E>"
	elseif line('.')==line('w0')
		exe "norm! \<C-Y>"
	endif
endfun
fun! OnResize()
	let numW=winnr('$')
	let curW=winnr()
	let scrR=
	\ eval(join(map(range(1,curW-1),"winheight(v:val)"),'+').'+winline()')
	if numW==1
		exe 'res '.(scrR+2)
	elseif s:iniW==1
		exe '1winc w|res '.scrR.'|norm! L'
	elseif s:iniW==numW
		exe numW.'winc w|res '.(&lines-scrR-numW).'|norm! H'
	elseif curW<s:iniW	
		for i in range(s:iniW-1,1,-1)
			if winheight(i)>1
				exe i.'winc w|res -1|'.numW.'winc w|res +1'
				break
			endif
		endfor
	elseif curW>s:iniW
		exe s:iniW.'winc w|res '.(min([&lines-1-2*numW+s:iniW,scrR])
		\ -join(map(range(1,s:iniW-1),'winheight(v:val)'),'+')).'|norm! L'
	else
		exe 'res '.min([&lines-1-scrR+winline()-2*numW+s:iniW,winline()])
	endif
endfun
fun! OnRelease()
	if g:MouseMode=='OnVisual'
		norm! v`v
	elseif g:MouseMode=='OnScroll' 
		exe 'se ve='.s:vesave
	endif
	let g:MouseMode='InitScroll'
endfun
nnoremap <silent> <leftmouse> <leftmouse>:call {g:MouseMode}()<CR>
nnoremap <silent> <leftrelease> <leftmouse>:call OnRelease()<CR>

fun! CapWait(prev)
	redraw
	let next=nr2char(getchar())
	if next=~'[.?!\r\n[:blank:]]'
		exe 'normal! i' . next . "\<Right>"
		return CapWait(next)
	elseif next=~'[\e\/]'
		return "\<del>"
	elseif a:prev=~'[\r\n[:blank:]]'
		return toupper(next) . "\<del>"
	else
		return next . "\<del>"
	endif
endfun
fun! CapHere()
	let trunc = getline(".")[0:col(".")-2] 
	return col(".")==1 ? CapWait("\r")
	\ : trunc=~'[?!.]\s*$\|^\s*$' ? CapWait(trunc[-1:-1]) : "\<del>"
endfun
imap <silent> . ._<Left><C-R>=CapWait('.')<CR>
imap <silent> ? ?_<Left><C-R>=CapWait('?')<CR>
imap <silent> ! !_<Left><C-R>=CapWait('!')<CR>
imap <silent> <CR> <CR>_<Left><C-R>=CapWait("\r")<R>
imap <silent> <NL> <NL>_<Left><C-R>=CapWait("\n")<CR>
nmap <silent> O O_<Left><C-R>=CapWait("\r")<CR>
nmap <silent> o o_<Left><C-R>=CapWait("\r")<CR>
nmap <silent> a a_<Left><C-R>=CapHere()<CR>
nmap <silent> A $a_<Left><C-R>=CapHere()<CR>
nmap <silent> i i_<Left><C-R>=CapHere()<CR>
nmap <silent> I I_<Left><C-R>=CapHere()<CR>
